package com.story.aistory.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.story.aistory.constants.JwtClaimsConstant;
import com.story.aistory.domain.dto.UserDTO;
import com.story.aistory.domain.dto.UserLoginDTO;
import com.story.aistory.domain.po.Result;
import com.story.aistory.domain.po.Users;
import com.story.aistory.domain.vo.UserLoginVO;
import com.story.aistory.enums.AppHttpCodeEnum;
import com.story.aistory.mapper.UsersMapper;
import com.story.aistory.service.IImagesService;
import com.story.aistory.service.IUsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.story.aistory.utils.*;
import lombok.RequiredArgsConstructor;
import org.apache.catalina.User;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hui
 * @since 2025-03-12
 */
@Service
@RequiredArgsConstructor
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService {
    @Override
    public Result<Users> getUser() {
        Users user = AppThreadLocalUtil.getUser();
        if (user.getId() == null) {
            return Result.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        Users users = getById(user.getId());
        return Result.success(users);
    }

    @Override
    public Result updateUserData(Users users) {

        Users user = AppThreadLocalUtil.getUser();
        // : 校验参数
        if (users == null || user.getId() == null ) {
            return Result.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        Users users1 = BeanUtils.copyBean(users, Users.class);
        users1.setId(user.getId());
        // : 更新用户信息
        updateById(users1);
        return Result.okResult(AppHttpCodeEnum.SUCCESS);
    }

    //微信服务接口地址
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";


    private final StringRedisTemplate redisTemplate;
    private final JwtProperties jwtProperties;
    private final WeChatProperties weChatProperties;
    private final IImagesService imagesService;

    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {
        String openid = getOpenid(userLoginDTO.getCode());
        //判断openid是否为空，如果为空表示登录失败，抛出业务异常
        if(openid == null){
            throw new RuntimeException("登录失败，请稍后再试");
        }
//        Users user = getUser(openid);
        Users user = getOne(new QueryWrapper<Users>().eq("openid", openid));
        //如果是新用户，自动完成注册
        if(user == null){
            user=Users.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now()).build();
            user.setCreateTime(LocalDateTime.now());
            save(user);
        }
        //为微信用户生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(token)
                .build();
        return  userLoginVO;
    }

    /**
     * 保存用户信息
     *
     */
    @Override
    public Result saveUserData(UserDTO userDTO) {
        Users user = AppThreadLocalUtil.getUser();
        // : 校验参数
        if (userDTO == null  || user.getId() == null) {
            return Result.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // : 更新用户信息
        Users users = BeanUtil.copyProperties(userDTO, Users.class);
        updateById(users);
        return Result.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 上传头像
     *
     */
    @Override
    public Result uploadAvatar(MultipartFile mpFile) {
        Integer userId = AppThreadLocalUtil.getUser().getId();
        String image = imagesService.uploadImage(mpFile, "avatars");
        if (image == null) {
            return Result.errorResult(AppHttpCodeEnum.PARAM_IMAGE_FORMAT_ERROR);
        }
        Users user = new Users();
        user.setId(userId);
        user.setAvatarUrl(image);
        updateById(user);
        return Result.success(image);
    }
    /**
     * 调用微信接口服务，获取微信用户的openid
     */
    private String getOpenid(String code){
        //调用微信接口服务，获得当前微信用户的openid
        Map<String, String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN, map);

        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        return openid;
    }
}
